package com.shycloud.common.minio;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.processing.OperationManager;
import com.qiniu.rtc.RtcRoomManager;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.shycloud.common.minio.service.MinioTemplate;
import com.shycloud.common.minio.service.QiniuUtils;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * minio 自动配置类
 *
 * @author npc
 */
@AllArgsConstructor
@EnableConfigurationProperties({MinioProperties.class})
public class MinioAutoConfiguration {
	private final MinioProperties properties;

	@Bean
	@ConditionalOnMissingBean(MinioTemplate.class)
	@ConditionalOnProperty(name = "qiniu.bucket")
	MinioTemplate template() {
		return new MinioTemplate(
				properties.getBucket(),
				properties.getAccessKey(),
				properties.getSecretKey(),
				properties.getCdn(),
				properties.getPrivateCdn(),
				properties.getPrivateBucket()
		);
	}

	@Bean
	@ConditionalOnMissingBean(QiniuUtils.class)
	@ConditionalOnProperty(name = "qiniu.bucket")
	QiniuUtils qiniuUtils() {
		return new QiniuUtils(
				properties.getRtcAppid());
	}
	/**
	 * 华东机房
	 */
	@Bean
	public com.qiniu.storage.Configuration qiniuConfig() {
		return new com.qiniu.storage.Configuration(Zone.zone0());
	}

	/**
	 * 构建一个七牛上传工具实例
	 */
	@Bean
	public UploadManager uploadManager() {
		return new UploadManager(qiniuConfig());
	}

	/**
	 * 构建一个七牛持久化数据处理实例
	 */
	@Bean
	public OperationManager operationManager() {
		return new OperationManager(auth(), qiniuConfig());
	}


	/**
	 * 认证信息实例
	 *
	 * @return
	 */
	@Bean
	public Auth auth() {
		return Auth.create(properties.getAccessKey(),
				properties.getSecretKey());
	}

	/**
	 * 构建七牛实时音频实例
	 */
	@Bean
	public RtcRoomManager rtcRoomManager() {
		return new RtcRoomManager (auth(), properties.getRtcCdn());
	}


	/**
	 * 构建七牛空间管理实例
	 */
	@Bean
	public BucketManager bucketManager() {
		return new BucketManager(auth(), qiniuConfig());
	}

	/**
	 * 配置gson为json解析工具
	 *
	 * @return
	 */
	@Bean
	public Gson gson() {
		return new Gson();
	}
}
